import { appCarsListGet, appCarsGetCarsCountGet, appCarsBatchDelGet, appCarsEditPost, appCarsSelectGet } from '@/api/shoppingCart.js'
function checkedAllInit (item) {
  if (item.shopSkuSellVoLists) {
    const len = item.shopSkuSellVoLists.length
    const checkedCount = item.shopSkuSellVoLists.filter((i) => i.isSelect === 'Y').length
    item.isSelect = checkedCount === len ? 'Y' : 'N'
    item.isIndeterminate = checkedCount > 0 && checkedCount < len
  } else {
    item.isSelect = 'N'
    item.isIndeterminate = false
  }
}
const useShoppingCartStore = defineStore('shoppingCart', {
  state: () => ({ count: 0, shopType: '', totalprice: 0, goodsList: [] }),
  actions: {
    setGoodsList () {
      return appCarsListGet().then((res) => {
        res.data.forEach((item) => {
          checkedAllInit(item)
        })
        this.goodsList = res.data
      })
    },
    setCount () {
      return appCarsGetCarsCountGet().then((res) => {
        this.count = parseInt(res.data.count)
        this.shopType = res.data.shopType
        this.totalprice = res.data.totalprice
      })
    },
    setItemInfo (item) {
      checkedAllInit(item)
    },
    deleteGoods (ids) {
      return appCarsBatchDelGet({ params: { ids } }).then((res) => {
        this.setGoodsList()
        this.setCount()
      })
    },
    editGoodsCount ({ skuId, count }) {
      return appCarsEditPost({ params: { skuId, count } }).then((res) => {
        this.shopType = res.data.shopType
        this.totalprice = res.data.totalprice
      })
    },
    selectGoods ({ ids, type }) {
      return appCarsSelectGet({ params: { ids, type } }).then((res) => {
        this.shopType = res.data.shopType
        this.totalprice = res.data.totalprice
      })
    },
    init () {
      return Promise.all([this.setGoodsList(), this.setCount()])
    }
  }
})

export default useShoppingCartStore